<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="搜索词" prop="searchTerms">
          <el-input
            v-model="queryParams.searchTerms"
            placeholder="搜索词"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="queryParams.status" class="!w-[100px]" clearable placeholder="全部">
            <el-option :value="0" label="入库前" />
            <el-option :value="1" label="已申请" />
            <el-option :value="2" label="已执行" />
            <el-option :value="3" label="已撤回" />
            <el-option :value="4" label="已作废" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryParams.createTime"
            :editable="false"
            class="!w-[240px]"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['project:importXml:add']" type="success" @click="handleOpenDialog()">
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['project:importXml:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          key="fromSite"
          label="来源网站"
          prop="fromSite"
          min-width="80"
          align="center"
        >
          <template #default="scope">
            <DictLabel v-model="scope.row.fromSite" :code="'from_web'" />
          </template>
        </el-table-column>
        <el-table-column
          key="searchTerms"
          label="搜索词"
          prop="searchTerms"
          min-width="400"
          align="center"
        />

        <el-table-column
          key="newArticlesNum"
          label="已入库数"
          prop="newArticlesNum"
          min-width="50"
          align="center"
        />
        <el-table-column
          key="oldArticlesNum"
          label="未入库数"
          prop="oldArticlesNum"
          min-width="50"
          align="center"
        />
        <el-table-column key="status" label="状态" prop="status" min-width="50" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 0" type="info">入库前</el-tag>
            <el-tag v-if="scope.row.status == 1" type="primary">已申请</el-tag>
            <el-tag v-if="scope.row.status == 2" type="success">已执行</el-tag>
            <el-tag v-if="scope.row.status == 3" type="danger">已撤回</el-tag>
            <el-tag v-if="scope.row.status == 4" type="warning">已作废</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          key="createTime"
          label="建立时间"
          prop="createTime"
          min-width="80"
          align="center"
        />
        <el-table-column
          key="updateTime"
          label="修改时间"
          prop="updateTime"
          min-width="80"
          align="center"
        />

        <el-table-column fixed="right" label="操作" width="350">
          <template #default="scope">
            <el-button
              v-hasPerm="['project:importXml:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
              v-if="scope.row.status == 0 || scope.row.status == 3"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['project:importXml:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id, true)"
              v-if="scope.row.status == 1 || scope.row.status == 2 || scope.row.status == 4"
            >
              <template #icon><Edit /></template>
              查看
            </el-button>
            <el-button
              v-hasPerm="['project:importXml:applyfor']"
              type="danger"
              size="small"
              link
              @click="handleApplyFor(scope.row.id)"
              v-if="scope.row.status == 0 || scope.row.status == 3"
            >
              <template #icon><Refrigerator /></template>
              申请入库
            </el-button>
            <el-button
              v-hasPerm="['project:importXml:inlib']"
              type="success"
              size="small"
              link
              @click="handleInLibDialog(scope.row.id)"
              v-if="scope.row.status == 1"
            >
              <template #icon><Upload /></template>
              执行入库
            </el-button>
            <el-button
              v-hasPerm="['project:importXml:inlib']"
              type="warning"
              size="small"
              link
              @click="handleCancel(scope.row.id)"
              v-if="scope.row.status == 0 || scope.row.status == 3"
            >
              <template #icon><Delete /></template>
              作废
            </el-button>
            <el-button
              v-hasPerm="['project:importXml:process']"
              type="info"
              size="small"
              link
              @click="handleProcess(scope.row.id)"
            >
              <template #icon><ScaleToOriginal /></template>
              处理过程
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 文章导入表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      top="3vh"
      width="1050"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="来源网站" prop="fromSite">
          <Dict v-model="formData.fromSite" code="from_web" />
        </el-form-item>
        <el-form-item label="搜索词" prop="searchTerms">
          <el-input v-model="formData.searchTerms" placeholder="搜索词" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            v-model="formData.content"
            placeholder="内容"
            class="custom-textarea"
            style="min-height: 480px; max-height: 500px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()" v-if="dialog.preview == false">
            确定
          </el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 执行入库 - 文章导入表单弹窗 -->
    <el-dialog
      v-model="dialog_inlib.visible"
      :title="dialog_inlib.title"
      top="3vh"
      width="1050"
      @close="handleCloseInLibDialog"
    >
      <el-form ref="dataInLibFormRef" :model="formData" :rules="rules_inlib" label-width="100px">
        <el-form-item label="来源网站" prop="fromSite">
          <Dict v-model="formData.fromSite" code="from_web" :disabled="true" />
        </el-form-item>
        <el-form-item label="搜索词" prop="searchTerms">
          <el-input v-model="formData.searchTerms" placeholder="搜索词" readonly />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            v-model="formData.content"
            placeholder="内容"
            class="custom-textarea"
            style="min-height: 480px; max-height: 500px"
            readonly
          />
        </el-form-item>
        <el-form-item label="入库操作" prop="targetType">
          <el-radio-group v-model="formData.targetType">
            <el-radio :value="1">入库</el-radio>
            <el-radio :value="2">回撤</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.targetType == 2" label="回撤原因" prop="reason">
          <el-input
            type="textarea"
            v-model="formData.reason"
            placeholder="回撤原因"
            class="reason-textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleInLibSubmit()">确定</el-button>
          <el-button @click="handleCloseInLibDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 处理详情 -->
    <ImportProcess ref="importProcessRef" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ImportXml",
  inheritAttrs: false,
});

import ImportXmlAPI, {
  ImportXmlPageVO,
  ImportXmlForm,
  ImportXmlPageQuery,
  ImportProcessContentForm,
} from "@/api/project/import-xml";
import ImportProcess from "../components/ImportProcess.vue";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const dataInLibFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const importProcessRef = ref();

// 获取路由参数
const route = useRoute();
const topicId = ref(route.query.id as string);
const topicTitle = ref(route.query.title as string);

const queryParams = reactive<ImportXmlPageQuery>({
  pageNum: 1,
  pageSize: 10,
  topicId: topicId.value,
});

// 监听路由参数变化，更新字典数据
watch(
  () => [route.query.id],
  ([newId]) => {
    queryParams.topicId = newId as string;
    topicId.value = newId as string;
    handleQuery();
  }
);

// 文章导入表格数据
const pageData = ref<ImportXmlPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
  preview: false,
});

// 弹窗
const dialog_inlib = reactive({
  title: "",
  visible: false,
});

// 文章导入表单数据
const formData = reactive<ImportXmlForm>({});
const formInLibData = reactive<ImportProcessContentForm>({});

// 文章导入表单校验规则
const rules = reactive({
  fromSite: [{ required: true, message: "请输入来源网站", trigger: "blur" }],
  searchTerms: [{ required: true, message: "请输入搜索词", trigger: "blur" }],
  content: [{ required: true, message: "请输入内容", trigger: "blur" }],
});

// 文章导入表单校验规则
const rules_inlib = reactive({
  fromSite: [{ required: true, message: "请输入来源网站", trigger: "blur" }],
  searchTerms: [{ required: true, message: "请输入搜索词", trigger: "blur" }],
  content: [{ required: true, message: "请输入内容", trigger: "blur" }],
  targetType: [{ required: true, message: "请选择入库操作", trigger: "blur" }],
});

/** 查询文章导入 */
function handleQuery() {
  loading.value = true;
  ImportXmlAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置文章导入查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  queryParams.createTime = undefined;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开文章导入弹窗 */
function handleOpenDialog(id?: number, preview: boolean = false) {
  dialog.visible = true;
  dialog.preview = preview;
  if (id) {
    if (preview === true) {
      dialog.title = "查看文章导入";
    } else {
      dialog.title = "修改文章导入";
    }

    ImportXmlAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增文章导入";
  }
}

/** 打开执行文章导入弹窗 */
function handleInLibDialog(id?: number) {
  dialog_inlib.visible = true;
  dialog_inlib.title = "文章导入";
  if (id) {
    ImportXmlAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  }
}

/** 作废文章导入 */
function handleCancel(id: number) {
  ElMessageBox.confirm("确认作废当前数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      loading.value = true;
      ImportXmlAPI.cancelById(id)
        .then(() => {
          ElMessage.success("作废成功");
          handleResetQuery();
        })
        .catch((error) => {
          console.error("作废失败:", error);
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      ElMessage.info("已取消作废");
    });
}

/** 提交文章导入表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        ImportXmlAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        formData.topicId = Number(topicId.value);
        ImportXmlAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 提交入库文章导入表单 */
function handleInLibSubmit() {
  dataInLibFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        formInLibData.id = id;
        formInLibData.targetType = formData.targetType;
        formInLibData.content = formData.reason;

        ImportXmlAPI.inLib(id, formInLibData)
          .then(() => {
            ElMessage.success("确认成功");
            handleCloseInLibDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ElMessage.warning("参数错误");
      }
    }
  });
}

/** 关闭文章导入弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 关闭入库文章导入弹窗 */
function handleCloseInLibDialog() {
  dialog_inlib.visible = false;
  dataInLibFormRef.value.resetFields();
  dataInLibFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除文章导入 */
function handleDelete(id?: number) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      ImportXmlAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

/** 申请文章导入 */
function handleApplyFor(id?: number) {
  ElMessageBox.confirm("确认申请入库?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      ImportXmlAPI.applyForById(id)
        .then(() => {
          ElMessage.success("申请入库成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消申请入库");
    }
  );
}

// 打开详情弹窗
function handleProcess(id: number) {
  importProcessRef.value.openProcess(id);
}

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.custom-textarea >>> .el-textarea__inner {
  min-height: 480px !important;
  max-height: 500px !important;
}
.reason-textarea >>> .el-textarea__inner {
  min-height: 80px !important;
  max-height: 100px !important;
}
</style>
